package com.wxtf.platform.main.contraceptives;

import java.util.ArrayList;
import java.util.List;  
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.ConstantInfoHelper;
import com.wxtf.platform.tools.FormatUtil;

public class TmaApplyAuditingMainAction extends LogicBase implements CommonsCallProvider  {

	private static Log log = LogFactory.getLog(TmaApplyAuditingMainAction.class);
	public TmaApplyAuditingMainAction(String jsonArray) {
	} 
	
	/** 
	 * 描述：delete 删除记录
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @author sun_xiaoliang
	 */
	@Override
	public Object delete(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		String[] ids = id.split(",");
		String sql = "delete from tma_apply_main where tmaam_id = ? and (tmaam_status=1 or tmaam_status=2) ";
		AccessDataBaseUtil.deleteByIds(sql, ids);
		return "\"删除成功\"";
	}

	/** 
	 * 描述：insert 增加入库记录
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @author sun_xiaoliang
	 */
	@Override
	public Object insert(Object jsonArray) throws Exception {		
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String tmaam_code = jsonObject.getString("tmaam_code");
		sql = "select count(*) from tma_apply_main where tmaam_code=?";
		List<Object> ls = AccessDataBaseUtil.query4List(sql,new Object[]{tmaam_code});
		int hasId = Integer.parseInt(ls.get(0).toString());
		if(hasId>0){
			return "\"出库编号不能重复\"";
		}
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean");
		String create_by = user.getUserId();
		String create_time = FormatUtil.getCurentDate();				
		String tmaam_id = AccessDataBaseUtil.getPKUUID();
		List<String> list = new ArrayList<String>();
		StringBuffer buff = new StringBuffer("insert into tma_apply_main(tmaam_id,org_id,tmaam_person,tmaam_code,tmaam_time,tmaam_status,create_by,create_time,last_modify_by,last_modify_time) values(");
		buff.append("'").append(tmaam_id).append("'")
		.append(",'").append(jsonObject.getString("org_id")).append("'")
		.append(",'").append(jsonObject.getString("tmaam_person")).append("'")
		.append(",'").append(tmaam_code).append("'")
		.append(",'").append(jsonObject.getString("tmaam_time")).append("'")
		.append(",'").append(jsonObject.getString("tmaam_status")).append("'")
		.append(",'").append(create_by).append("'")
		.append(",'").append(create_time).append("'")
		.append(",'").append(create_by).append("'")
		.append(",'").append(create_time).append("')");
		list.add(buff.toString());
		buff.setLength(0);
		String ids = jsonObject.getString("ids");
		array = JSONArray.fromObject(ids);
		for (int i=0;i<array.size();i++){
		    jsonObject = JSONObject.fromObject(array.getString(i)); 
			buff.append("insert into tma_apply_detail(tmaad_id,tmaam_id,tmad_id,tmaad_num,create_by,create_time,last_modify_by,last_modify_time) values(")
			.append("'").append(AccessDataBaseUtil.getPKUUID()).append("'")
			.append(",'").append(tmaam_id).append("'")
			.append(",'").append(jsonObject.getString("tmad_id")).append("'")
			.append(",'").append(jsonObject.getString("tmaad_num")).append("'")
			.append(",'").append(create_by).append("'")
			.append(",'").append(create_time).append("'")
			.append(",'").append(create_by).append("'")
			.append(",'").append(create_time).append("')");
			list.add(buff.toString());
			buff.setLength(0);
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"新建成功\"";
	}

	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	/** 
	 * 描述：select 查询载入
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @author sun_xiaoliang
	 */
	@Override
	public Object select(Object jsonArray) throws Exception {
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean");
		String CurOrgId = user.getCurOrgId();
		sql = " from tma_apply_main o,t_user u,t_department d , t_department d2 where o.create_by=u.user_id and o.org_id=d.department_id and d.DPARENT_ID=d2.DEPARTMENT_ID and d.DPARENT_ID= '"+CurOrgId+"' and o.tmaam_status<>1 order by tmaam_status desc,tmaam_code desc";
		String countSql = "select count(tmaam_id) " + sql;
		String querySql = "select tmaam_id,d.caption as org_id,tmaam_code,tmaam_time,   tmaam_status   ,u.caption as create_by,d.CAPTION,d2.CAPTION as CAPTION2,tmaam_person ,tmaam_status,tmaam_content,tmaam_memo,reserve1, create_by,create_time,last_modify_by,last_modify_time" + sql;
		String[] fields = {"tmaam_id","org_id","tmaam_code","tmaam_time","tmaam_status","create_by","CAPTION","CAPTION2","tmaam_person", "tmaam_status","tmaam_content","tmaam_memo","reserve1", "create_by","create_time","last_modify_by","last_modify_time"};
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), null);
	} 
	
	/** 
	 * 描述：run 载入
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @author sun_xiaoliang
	 */
	@Override
	public Object run() {
		Object msg = "";
		try {
			if ("queryPage".equals(this.getMethodName())) {// 列表
				msg = this.select(this.getLogicData());
				return msg.toString();
			} else if ("update".equals(this.getMethodName())) {// 修改
				msg = this.update(this.getLogicData());
			} else if ("save".equals(this.getMethodName())) {// 添加
				msg = this.insert(this.getLogicData());
			} else if ("delete".equals(this.getMethodName())) {// 删除
				msg = this.delete(this.getLogicData());
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}
			if(msg == null || "[null]".equals(msg)){
				msg = "\"\"";
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
		} catch (Exception e) {
			msg = "操作失败，请联系管理员";
			msg = ConstantInfoHelper.generateJSONString(ConstantInfoHelper.JSON_HEAD, ConstantInfoHelper.getFailResultDetail(msg.toString()), false);
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}
 
	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return request;
	}
	String[] fields = {"tmaam_id","tmaam_status","tmaam_content", 
			"reserve1","last_modify_by","last_modify_time"
	};
 
	
	String[] fields2 = {"tmaad_id","tmaam_id","tmad_id","tmaad_num",
			"reserve1","reserve2","reserve3","reserve4","reserve5","create_by","create_time","last_modify_by","last_modify_time"
	};
 
	/** 
	 * 描述：update 更新记录
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @author sun_xiaoliang
	 */
	@Override
	public Object update(Object jsonArray) throws Exception {
 
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0)); 
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean");
		String tmaam_id =  jsonObject.getString("tmaam_id");
		String CurOrgId = user.getCurOrgId();
		String create_by = user.getUserId();
		String create_byName = user.getUserrelName();
		String create_time = FormatUtil.getCurentDate(); 
		List<String> list = new ArrayList<String>();
		StringBuffer buff = new StringBuffer();
 
		
		
 
		sql = "select count(*) from tma_outcome_main where tmaom_id=?";
		List<Object> ls1 = AccessDataBaseUtil.query4List(sql,new Object[]{tmaam_id});
		int hasId1 = Integer.parseInt(ls1.get(0).toString());
		
		sql = "select count(*) from tma_income_main where tmaim_id=?";
		List<Object> ls2 = AccessDataBaseUtil.query4List(sql,new Object[]{tmaam_id});
		int hasId2 = Integer.parseInt(ls2.get(0).toString());
		
		buff.append("update tma_apply_main set ");
		Object[] obj = new Object[fields.length];
		
		for(int j = 1; j < fields.length; j++) {
			obj[j] = jsonObject.getString(fields[j]); 
		}
		obj[fields.length-2]  =  create_by;
		obj[fields.length-1]  =  create_time;
		
		for(int j = 1; j < fields.length; j++) {
				buff.append(fields[j]).append("='").append(obj[j]).append("',");
		}
		buff.deleteCharAt(buff.length() - 1).append(" where tmaam_id = '" +tmaam_id).append("'");
		list.add(buff.toString());
		buff.setLength(0);
 
		//插入出库主表
		if(hasId1==0){
 
			buff.append("Insert into tma_outcome_main ")      
			.append("(").append("tmaom_id") //1
			.append(",").append("org_id")   //2
			.append(",").append("tmaom_type") //3
			.append(",").append("tmaom_is_valid")//4
			.append(",").append("tmaom_code")     //5
			.append(",").append("tmaom_time")     // 6     
			.append(",").append("reserve1")         //7
			.append(",").append("create_by")        //8
			.append(",").append("create_time")      //9  
			.append(",").append("last_modify_by")     //10   
			.append(",").append("last_modify_time")     //11   
			.append(")").append("select ")
			.append(" ").append("tmaam_id")   //1
			.append(",'" +CurOrgId+ "'")       //2
			.append(",").append("'0'")        //3 自动出库类型
			.append(",").append("'0'")        //4 冲红
			.append(",").append("tmaam_code") //5 这个需要计算 
			.append(",'").append(create_time).append("'") //6
			.append(",").append("reserve1")                  //7
			.append(",'").append(create_by).append("'")      //8
			.append(",'").append(create_time).append("'")    //9 
			.append(",'").append(create_by).append("'")  
			.append(",'").append(create_time).append("'")    //11
			.append(" ").append("FROM tma_apply_main where ")
			.append(" ").append("tmaam_id='" +tmaam_id).append("'")
			.append(" ");
			list.add(buff.toString());
			buff.setLength(0);
			
			//插入出库子表 
			buff.append("Insert into tma_outcome_detail ")      
			.append("(").append("tmaod_id")    //1
			.append(",").append("tmaom_id")    //2
			.append(",").append("tmad_id")     //3
			.append(",").append("tmaod_num")   //4
			.append(",").append("create_by")        //5
			.append(",").append("create_time")      //6  
			.append(",").append("last_modify_by")   //7   
			.append(",").append("last_modify_time") //8   
			.append(")").append("select ")
			.append(" ").append("tmaad_id")      //1
			.append(",").append("tmaam_id")      //2
			.append(",").append("tmad_id")       //3 
			.append(",").append("tmaad_num")     //4 
			.append(",'").append(create_by).append("'")      //5
			.append(",'").append(create_time).append("'")    //6
			.append(",'").append(create_by).append("'")      //7
			.append(",'").append(create_time).append("'")    //8
			.append(" ").append("FROM tma_apply_detail where ")
			.append(" ").append("tmaam_id='" +tmaam_id).append("'")
			.append(" ");
			list.add(buff.toString()); 
			buff.setLength(0);
		}
		
		//插入入库主表
		if(hasId2==0){
			buff.append("Insert into tma_income_main ")      
			.append("(").append("tmaim_id") //1
			.append(",").append("org_id")   //2
			.append(",").append("tmaim_type") //3
			.append(",").append("tmaim_is_valid")//4
			.append(",").append("tmaim_code")     //5
			.append(",").append("tmaim_time")     // 6     
			.append(",").append("reserve1")         //7
			.append(",").append("create_by")        //8
			.append(",").append("create_time")      //9  
			.append(",").append("last_modify_by")     //10   
			.append(",").append("last_modify_time")     //11  
			.append(")").append("select ")
			.append(" ").append("tmaam_id")   //1
			.append(",").append("org_id")     //2
			.append(",").append("'0'")        //3 自动出库类型
			.append(",").append("'0'")        //4 冲红
			.append(",").append("tmaam_code") //5 这个需要计算 
			.append(",'").append(create_time).append("'") //6
			.append(",").append("reserve1")                  //7
			.append(",'").append(create_by).append("'")      //8
			.append(",'").append(create_time).append("'")    //9
			.append(",'").append(create_by).append("'")      //10
			.append(",'").append(create_time).append("'")    //11
			.append(" ").append("FROM tma_apply_main where ")
			.append(" ").append("tmaam_id='" +tmaam_id).append("'")
			.append(" ");
			list.add(buff.toString());
			buff.setLength(0);
			
			//插入入库子表
	 
			buff.append("Insert into TMA_INCOME_DETAIL ")      
			.append("(").append("tmaid_id")    //1
			.append(",").append("tmaim_id")    //2
			.append(",").append("tmad_id")     //3
			.append(",").append("tmaid_num")   //4
			.append(",").append("create_by")        //5
			.append(",").append("create_time")      //6  
			.append(",").append("last_modify_by")   //7   
			.append(",").append("last_modify_time") //8   
			.append(")").append("select ")
			.append(" ").append("tmaad_id")      //1
			.append(",").append("tmaam_id")      //2
			.append(",").append("tmad_id")       //3 
			.append(",").append("tmaad_num")     //4 
			.append(",'").append(create_by).append("'")      //5
			.append(",'").append(create_time).append("'")    //6
			.append(",'").append(create_by).append("'")      //7
			.append(",'").append(create_time).append("'")    //8
			.append(" ").append("FROM tma_apply_detail where ")
			.append(" ").append("tmaam_id='" +tmaam_id).append("'")
			.append(" ");
		}
		list.add(buff.toString()); 
		buff.setLength(0);
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"保存成功\"";
	}
	
	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object onInit(Object jsonArray) {
		// TODO Auto-generated method stub
		return null;
	}

}
